package com.lovestudying.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.aliyuncs.exceptions.ClientException;
import com.lovestudying.entity.Account;
import com.lovestudying.service.AccountService;
import com.lovestudying.service.impl.AccountServiceImpl;
import com.lovestudying.util.AliSMSUtil;
import com.lovestudying.util.DBUtil_Pro;
import com.lovestudying.util.PageInfo;

/**
 * Servlet implementation class AccountRegisterServlet
 */
@WebServlet("/AccountRegisterServlet")
@MultipartConfig
public class AccountRegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// 调用业务层AccountService-AccountServiceImpl
	private AccountService accountService = new AccountServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AccountRegisterServlet() {

		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取op属性值（前端jsp页面、ajax异步请求传进来的值）
		String op = request.getParameter("op");

		// 进行判断
		if ("existsOfAccountName".equals(op)) {
			// 判断用户名是否存在
			accountNameExist(request, response);

		} else if ("getAccountByphone".equals(op)) {
			// p判断手机号是否存在
			doGetAccountByphone(request, response);
		} else if ("getAccountByemail".equals(op)) {
			// 判断电子邮件地址是否存在
			doGetAccountByemail(request, response);
		} else if ("getVerificationCode".equals(op)) {
			try {
				doGetVerificationCode(request, response);
			} catch (ClientException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void doGetVerificationCode(HttpServletRequest request, HttpServletResponse response)
			throws ClientException, IOException {
		// 获取手机号
		String phone = request.getParameter("phone");
		// 获取flag
		String flag = request.getParameter("flag");
		if (flag == "") {
			String sendCode = AliSMSUtil.sendCode(phone);
			System.out.println(sendCode);
			// 将验证码存储在cookies中
			Cookie cookie = new Cookie("sendCode", sendCode);
			// 设置cookie失效时间5分钟
			cookie.setMaxAge(5 * 60 * 1000);
			response.addCookie(cookie);
			// 响应给前台jsp
			response.getWriter().write("succeed");
		} else {
			Cookie c = null;
			// 获取用户输入的验证码
			String inputCode = request.getParameter("inputCode");
			// 从cookie中获取生成的验证码
			Cookie[] cookies = request.getCookies();
			for (int i = 0; i < cookies.length; i++) {
				c = cookies[i];
			}
			if ("sendCode".equals(c.getName())) {
				// 响应给前台jsp
				response.getWriter().write(c.getValue());
			} else {

				// 响应给前台jsp
				response.getWriter().write("false");
				
			}
		}
	}

	private void doGetAccountByemail(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置一个标杆
		String flag = "false";

		// 获取用户名
		String email = request.getParameter("email");

		// 获取所有 List<Account>、不需要任何条件
		PageInfo<Account> pageInfo = accountService.getAccount();
		List<Account> list = pageInfo.getData();

		// 进行遍历
		for (Account account : list) {
			if (account.getAccount_email().equals(email)) {
				flag = "true";
			}
		}

		// 响应给前台jsp
		response.getWriter().write(flag);

	}

	private void doGetAccountByphone(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置一个标杆
		String flag = "false";

		// 获取用户名
		String phone = request.getParameter("phone");

		// 获取所有 List<Account>、不需要任何条件
		PageInfo<Account> pageInfo = accountService.getAccount();
		List<Account> list = pageInfo.getData();

		// 进行遍历
		for (Account account : list) {
			if (account.getAccount_phone().equals(phone)) {
				flag = "true";
			}
		}

		// 响应给前台jsp
		response.getWriter().write(flag);

	}

	private void doRegister(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// 接收裁剪图片坐标参数
		Integer x = new Double(Double.parseDouble(request.getParameter("pic-x"))).intValue();
		Integer y = new Double(Double.parseDouble(request.getParameter("pic-y"))).intValue();
		Integer destWidth = new Double(Double.parseDouble(request.getParameter("destWidth"))).intValue();
		Integer destHeight = new Double(Double.parseDouble(request.getParameter("destHeight"))).intValue();
		Integer finalWidth = new Double(Double.parseDouble(request.getParameter("finalWidth"))).intValue();
		Integer finalHeight = new Double(Double.parseDouble(request.getParameter("finalHeight"))).intValue();
		// 接受普通组件
		String accountName = request.getParameter("accountName");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String md5Password = DBUtil_Pro.getMd5(password);
		Account account = accountService.getAccountByPhone(phone);
		String accountPic = account.getAccount_pic();
		HttpSession session = request.getSession();
		// 将对象存入session作用域中
		session.setAttribute("phone", phone);

		session.setAttribute("name", accountName);

		// 接受文件组件
		Part part = request.getPart("facePicture");

		// 判断用户是否有上传文件
		if (part.getSize() == 0) { // 没有上传
			// 业务逻辑层
			accountService.AccountRegister(phone, accountName, email, md5Password, null, 1, 0);
		} else { // 有上传
			// 允许的文件图片类型
			String allowImgType = "image/jpg,image/jpeg,image/png";
			// 允许的文件图片类型集合
			List<String> allowImgTypeList = Arrays.asList(allowImgType.split(","));

			// 判断上传的文件类型是否合法
			String contentType = part.getContentType(); // 获取上传文件的MIME类型
			if (allowImgTypeList.contains(contentType) == false) {
				System.out.println("文件类型不匹配!");
				// 重定向注册页面,提示文件不合法
				response.sendRedirect("front/register.jsp?fileuploaderror=fileuploaderror");
				return;
			} else {
				// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
				String header = part.getHeader("content-disposition");
				String realName = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
				// 获取真实文件名的后缀
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
				// JDK1.8 日期时间类
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				// 将当前日期时间转成字符串
				String formatDate = ofPattern.format(now);
				// 随机数
				int random = (int) (Math.random() * 1000 + 1);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(formatDate).append(random);

				// 将文件存储在指定服务器中(本地电脑D盘)
				File file = new File("D:\\fileupload\\images");
				// 目录如果不存在，则创建
				if (!file.exists()) {
					file.mkdirs();
				} else {
					// 将文件写入指定位置
					String filePath = file.getPath() + File.separator + fileName + fileSuffix;
					part.write(filePath);
					// 重读取并裁剪头像
					DBUtil_Pro.abscut(filePath, x, y, destWidth, destHeight, finalWidth, finalHeight);
				}
				session.setAttribute("accountPic", fileName + fileSuffix);
				// 调用业务层
				// 数据库中仅需要存储文件名.扩展名
				accountService.AccountRegister(phone, accountName, email, md5Password, fileName + fileSuffix, 1, 0);
			}
		}
		// 重定向到前台首页
		;
		session.setAttribute("accountId", accountService.getAccountByPhone(phone).getAccount_id());
		response.sendRedirect("front/index2.jsp");
	}

	private void accountNameExist(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置一个标杆
		String flag = "false";

		// 获取用户名
		String accountName = request.getParameter("accountName");

		// 获取所有 List<Account>、不需要任何条件
		PageInfo<Account> pageInfo = accountService.getAccount();
		List<Account> list = pageInfo.getData();

		// 进行遍历
		for (Account account : list) {
			if (account.getAccount_name().equals(accountName)) {
				flag = "true";
			}
		}

		// 响应给前台jsp
		response.getWriter().write(flag);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String op = request.getParameter("op");
		if ("register".equals(op)) {
			// 注册
			doRegister(request, response);
		}
		/* doGet(request, response); */
	}

}
